package org.luxor.commons.zookeeper.component;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.*;
import org.luxor.commons.zookeeper.config.properties.ZookeeperProperties;
import org.springframework.util.Assert;

import java.util.Optional;

/**
 * Watcher Manager
 *
 * @author Mr.Yan  @date: 2020/12/22
 */
public class WatcherManager {
    private NodeCacheWatcher nodeCacheWatcher;
    private PathChildrenCacheWatcher pathChildrenCacheWatcher;
    private TreeCacheWatcher treeCacheWatcher;

    /**
     * 初始化 监听器
     */
    public  WatcherManager(CuratorFramework curatorFramework, ZookeeperProperties zookeeperProperties) {
        Assert.notNull(zookeeperProperties, "zookeeperProperties has not been instantiated yet");
        Assert.notNull(curatorFramework, "curatorFramework has not been instantiated yet");

        nodeCacheWatcher = new NodeCacheWatcher(curatorFramework, zookeeperProperties);
        pathChildrenCacheWatcher = new PathChildrenCacheWatcher(curatorFramework, zookeeperProperties);
        treeCacheWatcher = new TreeCacheWatcher(curatorFramework, zookeeperProperties);
    }


    /**
     * 添加 节点监听器
     *
     * @param nodeCacheListener 监听接收器
     */
    public void addNodeWatcher(String path, NodeCacheListener nodeCacheListener) throws Exception {
        nodeCacheWatcher.addWatcher(path, nodeCacheListener);
    }

    /**
     * 获取 节点监听器
     */
    public Optional<NodeCache> getNodeWatcher(String path) {
        return nodeCacheWatcher.getWatcher(path);
    }

    /**
     * 移除 节点监听器
     */
    public void removeNodeWatcher(String path) {
        nodeCacheWatcher.removeWatcher(path);
    }


    /**
     * 添加 子节点监听器
     *
     * @param pathChildrenCacheListener 监听接收器
     */
    public void addPathChildrenWatcher(String path, PathChildrenCacheListener pathChildrenCacheListener) throws Exception {
        pathChildrenCacheWatcher.addWatcher(path, pathChildrenCacheListener);
    }

    /**
     * 获取 子节点监听器
     */
    public Optional<PathChildrenCache> getPathChildrenWatcher(String path) {
        return pathChildrenCacheWatcher.getWatcher(path);
    }

    /**
     * 移除 子节点监听器
     */
    public void removePathChildrenWatcher(String path) {
        pathChildrenCacheWatcher.removeWatcher(path);
    }


    /**
     * 添加 子节点监听器
     *
     * @param treeCacheListener 监听接收器
     */
    public void addTreeWatcher(String path, TreeCacheListener treeCacheListener) throws Exception {
        treeCacheWatcher.addWatcher(path, treeCacheListener);
    }

    /**
     * 获取 子节点监听器
     */
    public Optional<TreeCache> getTreeWatcher(String path) {
        return treeCacheWatcher.getWatcher(path);
    }

    /**
     * 移除 子节点监听器
     */
    public void removeTreeWatcher(String path) {
        treeCacheWatcher.removeWatcher(path);
    }

}
